package com.tensquare.friend.interceptor;

import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * preHandle  前置拦截
     */

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("经过了拦截器");
        //无论如何都放行 具体能不能操作还是在具体的业务中去判断
        //拦截器只是负责把有请求头中包含token的令牌进行一个解析验证
        //通过request对象获取请求头
        String header = request.getHeader("Authorization");
        if (null != header && !"".equals(header)){
            //再次进行判断是否以Bearer 开头
            if (header.startsWith("Bearer ")){
                String token = header.substring(7);
                if (null != token && !"".equals(token)){
                    //对令牌进行验证
                    try {
                        Claims claims = jwtUtil.parseJWT(token);
                        String roles = (String) claims.get("roles");
                        if (null != roles && roles.equals("admin")) {
                            //相当于它是一个管理员的权限
                            request.setAttribute("claims_admin", claims);
                        }
                        if (null != roles && roles.equals("user")){
                            //相当于他是一个普通用户
                            request.setAttribute("claims_user",claims);
                        }
                    }catch (Exception e){
                        throw new RuntimeException("令牌不正确！");
                    }
                }
            }
        }
        return true;
    }
}
